package com.dge.app.ui

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Message
import android.webkit.JavascriptInterface
import android.webkit.WebSettings
import com.blankj.utilcode.util.BarUtils
import com.dge.app.R
import com.dge.app.databinding.ActivityWebviewBinding
import com.dge.common.base.view.BaseActivity
import com.dge.common.common.AppConfig
import com.dge.common.common.Constants
import com.dge.common.common.UserInfoMgr
import com.dge.common.extentions.color
import com.dge.common.extentions.gone
import com.dge.common.extentions.isValid
import com.dge.common.extentions.margin
import com.dge.common.extentions.singleClick
import com.dge.common.livedata.LifecycleHandler
import com.dge.common.widgets.view.BrowserView
import timber.log.Timber

class WebViewActivity : BaseActivity<ActivityWebviewBinding>() {
    companion object {
        const val WHAT_MSG_CHANGE_TITLE = 0x100
        const val EXTRA_URL = "extra_url"
        const val EXTRA_TITLE = "extra_title"
        const val EXTRA_IS_USE_WIDE_VIEW_PORT = "extra_is_use_wide_view_port"
        const val EXTRA_IS_ZOOM_IN = "extra_is_zoom_in" //是否支持放大和缩小
        const val EXTRA_IS_EXIT_DIRECTLY = "extra_is_exit_directly" //是否支持一次性退出
        const val EXTRA_IS_USER_WEB_TITLE = "extra_is_user_web_title" //是否使用WebView的title
        const val EXTRA_FUN_JSON_DATA = "extra_fun_json_data"
        const val EXTRA_STATISTIC_JSON_DATA = "extra_statistic_json_data"

        fun launcher(
            context: Context, url: String?, name: String?,
            jsonData: String = "",
            statisticJsonData: String = "",
            isUseWideViewPort: Boolean = true,
            isZoomIn: Boolean = false,
            isExitDirectly: Boolean = false,
            isUseWebTitle: Boolean = false
        ) {
            val intent = Intent(context, WebViewActivity::class.java)
            intent.putExtra(EXTRA_URL, url)
            intent.putExtra(EXTRA_TITLE, name)
            intent.putExtra(EXTRA_IS_USE_WIDE_VIEW_PORT, isUseWideViewPort)
            intent.putExtra(EXTRA_IS_ZOOM_IN, isZoomIn)
            intent.putExtra(EXTRA_IS_EXIT_DIRECTLY, isExitDirectly)
            intent.putExtra(EXTRA_IS_USER_WEB_TITLE, isUseWebTitle)
            intent.putExtra(EXTRA_FUN_JSON_DATA, jsonData)
            intent.putExtra(EXTRA_STATISTIC_JSON_DATA, statisticJsonData)
            if (context !is Activity)
                intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            context.startActivity(intent)
            Timber.i(url)
        }
    }

    var handler = MyHandler()
    var url = ""
    var title = ""
    var isUseWideViewPort = true
    var isZoomIn = false
    var isExitDirectly = false
    var isUseWebTitle = false
    var funcJsonData = ""
    var statisticJsonData = ""
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        getExtras(savedInstanceState)
        binding.titleBar.gone()
        binding.webView.margin(topMargin = BarUtils.getStatusBarHeight())
        init()
        initListeners()
    }

    private fun initListeners() {
        binding.ivClose.singleClick {
            finish()
        }
    }

    private fun getExtras(bundle: Bundle?) {
        if (bundle == null) {
            url = intent.getStringExtra(EXTRA_URL) ?: ""
            title = intent.getStringExtra(EXTRA_TITLE) ?: ""
            isUseWideViewPort = intent.getBooleanExtra(EXTRA_IS_USE_WIDE_VIEW_PORT, true)
            isZoomIn = intent.getBooleanExtra(EXTRA_IS_ZOOM_IN, false)
            isExitDirectly = intent.getBooleanExtra(EXTRA_IS_EXIT_DIRECTLY, false)
            isUseWebTitle = intent.getBooleanExtra(EXTRA_IS_USER_WEB_TITLE, false)
            funcJsonData = intent.getStringExtra(EXTRA_FUN_JSON_DATA) ?: ""
            statisticJsonData = intent.getStringExtra(EXTRA_STATISTIC_JSON_DATA) ?: ""
        } else {
            url = bundle.getString(EXTRA_URL) ?: ""
            title = bundle.getString(EXTRA_TITLE) ?: ""
            isUseWideViewPort = bundle.getBoolean(EXTRA_IS_USE_WIDE_VIEW_PORT, true)
            isZoomIn = bundle.getBoolean(EXTRA_IS_ZOOM_IN, false)
            isExitDirectly = bundle.getBoolean(EXTRA_IS_EXIT_DIRECTLY, false)
            isUseWebTitle = bundle.getBoolean(EXTRA_IS_USER_WEB_TITLE, false)
            funcJsonData = bundle.getString(EXTRA_FUN_JSON_DATA) ?: ""
            statisticJsonData = bundle.getString(EXTRA_STATISTIC_JSON_DATA) ?: ""
        }
    }

    override fun onSaveInstanceState(outState: Bundle) {
        outState.putString(EXTRA_URL, url)
        outState.putString(EXTRA_TITLE, title)
        outState.putBoolean(EXTRA_IS_USE_WIDE_VIEW_PORT, isUseWideViewPort)
        outState.putBoolean(EXTRA_IS_ZOOM_IN, isZoomIn)
        outState.putBoolean(EXTRA_IS_EXIT_DIRECTLY, isExitDirectly)
        outState.putBoolean(EXTRA_IS_USER_WEB_TITLE, isUseWebTitle)
        outState.putString(EXTRA_FUN_JSON_DATA, funcJsonData)
        outState.putString(EXTRA_STATISTIC_JSON_DATA, statisticJsonData)
        super.onSaveInstanceState(outState)
    }

    override fun setSystemBarColor(isfitWindow: Boolean, isLight: Boolean, colorResId: Int) {
        super.setSystemBarColor(false, true, R.color.transparent)
    }

    private fun init() {
        binding.titleBar.title = title
        if (isExitDirectly) {
            binding.ivClose.gone()
        }
        binding.webView.setLifecycleOwner(this)
        binding.webView.settings.databaseEnabled = true
        binding.webView.settings.useWideViewPort = isUseWideViewPort
        binding.webView.settings.userAgentString = binding.webView.settings.userAgentString + "android"
        binding.webView.settings.setRenderPriority(WebSettings.RenderPriority.HIGH)
        binding.webView.settings.setSupportZoom(isZoomIn)
        binding.webView.setBackgroundColor(R.color.colorWhiteEEEEEE.color())
        binding.webView.settings.blockNetworkImage = false //解决图片不显示
        val isDarkTheme = AppConfig.isDarkTheme()
        Timber.i("isDarkTheme = $isDarkTheme")
        binding.webView.setBrowserViewClient(BrowserView.BrowserViewClient(binding.webView))
        binding.webView.setBrowserChromeClient(object : BrowserView.BrowserChromeClient(binding.webView) {
            override fun onProgressChanged(view: android.webkit.WebView?, newProgress: Int) {
                binding.progressBar.progress(newProgress)
            }

            override fun onReceivedTitle(view: android.webkit.WebView?, title: String?) {
                Timber.i("onReceivedTitle title = $title")
                if (isUseWebTitle) {
                    title?.let {
                        handler.removeMessages(WHAT_MSG_CHANGE_TITLE)
                        if (isFinished()) return
                        val msg = Message()
                        msg.what = WHAT_MSG_CHANGE_TITLE
                        msg.obj = it
                        handler.sendMessageDelayed(msg, 500) //切换过程中可能会跳多个title，用这种方式只显示最后一个title
                    }
                }
            }
        })
        binding.webView.addJavascriptInterface(this, "android")
        url = intent.getStringExtra(EXTRA_URL) ?: ""
        Timber.i("url = $url")
        if (url.isValid()) {
            binding.webView.loadUrl(url)
        }
    }

    @JavascriptInterface
    fun addApplication(json: String) {
        Timber.i("addApplication json = $json")
        UserInfoMgr.functionData = json
        UserInfoMgr.saveUserInfo(Constants.firstIn)
        setResult(RESULT_OK)
    }

    @JavascriptInterface
    fun addOverview(json: String) {
        Timber.i("addOverview json = $json")
        UserInfoMgr.statisticsData = json
        UserInfoMgr.saveUserInfo(Constants.firstIn)
        setResult(RESULT_OK)
    }

    @JavascriptInterface
    fun getOverviews(): String {
        Timber.i("getOverview")
        return UserInfoMgr.statisticsData
    }

    @JavascriptInterface
    fun getApplications(): String {
        Timber.i("getApplications")
        return UserInfoMgr.functionData
    }

    @JavascriptInterface
    fun back() {
        setResult(RESULT_OK)
        finish()
    }

    @Deprecated("Deprecated in Java")
    override fun onBackPressed() {
        if (binding.webView.canGoBack())
            binding.webView.goBack() //后退
        else {
            setResult(RESULT_OK)
            super.onBackPressed()
        }
    }

    inner class MyHandler : LifecycleHandler(this) {
        override fun handleMessage(msg: Message) {
            if (msg.what == WHAT_MSG_CHANGE_TITLE) {
                if (isFinished()) return
                val title = msg.obj as? String
                title?.let {
                    binding.titleBar.title = it
                }
            }
        }
    }
}